package com.ewhale.feitengguest.ui.auth;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.ArticleDetailDto;
import com.ewhale.feitengguest.dto.LoginInfoDto;
import com.ewhale.feitengguest.dto.OriginDataDto;
import com.ewhale.feitengguest.dto.TabEntity;
import com.ewhale.feitengguest.presenter.user.auth.LoginPresenter;
import com.ewhale.feitengguest.receiver.TagAliasOperatorHelper;
import com.ewhale.feitengguest.ui.WebViewActivity;
import com.ewhale.feitengguest.ui.shop.ShopMainActivity;
import com.ewhale.feitengguest.ui.user.MainActivity;
import com.ewhale.feitengguest.utils.Contants;
import com.ewhale.feitengguest.utils.UserInfoUtils;
import com.ewhale.feitengguest.view.auth.LoginView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.http.JsonUtil;
import com.simga.library.utils.CheckUtil;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.LogUtil;
import com.simga.library.utils.StringUtil;
import com.simga.library.widget.BGButton;

import java.util.ArrayList;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiguang.share.android.api.AuthListener;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.model.AccessTokenInfo;
import cn.jiguang.share.android.model.BaseResponseInfo;
import cn.jiguang.share.android.model.UserInfo;

import static com.ewhale.feitengguest.receiver.TagAliasOperatorHelper.ACTION_SET;
import static com.ewhale.feitengguest.receiver.TagAliasOperatorHelper.sequence;

public class LoginActivity extends MBaseActivity<LoginPresenter> implements LoginView {
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.btn_login)
    BGButton mBtnLogin;
    @BindView(R.id.btn_register)
    BGButton mBtnRegister;
    @BindView(R.id.topMainTab)
    CommonTabLayout topMainTab;
    @BindView(R.id.iv_qq)
    ImageView ivQq;

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    public static void open(MBaseActivity mContext) {
        mContext.startActivity(null, LoginActivity.class);
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setTitle("登录");
        if (!Hawk.get(HawkKey.IS_USER_LOGIN, false) && !Hawk.get(HawkKey.IS_SHOP_LOGIN, false)) {
            mTabEntities.add(new TabEntity("我是用户", 0, 0));
            mTabEntities.add(new TabEntity("我是商家", 0, 0));
        } else {
            if (!Hawk.get(HawkKey.IS_SHOP_LOGIN, false)) {
                mTabEntities.add(new TabEntity("我是商家", 0, 0));
//                ivQq.setVisibility(View.GONE);
            } else if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                mTabEntities.add(new TabEntity("我是用户", 0, 0));
            }
        }
        topMainTab.setTabData(mTabEntities);
//        mEtPhone.setText("15622129191");
//        mEtPassword.setText("123456");
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return true;
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }

    @Override
    protected void initListener() {
        super.initListener();
//        topMainTab.setOnTabSelectListener(new OnTabSelectListener() {
//            @Override
//            public void onTabSelect(int position) {
//                ivQq.setVisibility(position == 1 ? View.GONE : View.VISIBLE);
//            }
//            @Override
//            public void onTabReselect(int position) {
//
//            }
//        });
    }

    @OnClick({R.id.btn_login, R.id.btn_forget, R.id.iv_wechat, R.id.iv_qq,
            R.id.btn_register, R.id.tv_xieyi, R.id.tv_privacy})
    public void onViewClicked(View view) {
        String loginPhone;
        String loginPwd;
        switch (view.getId()) {
            case R.id.btn_login:
                loginPhone = mEtPhone.getText().toString();
                loginPwd = mEtPassword.getText().toString();
                if (CheckUtil.isNull(loginPhone)) {
                    showToast("请输入手机号码");
                    return;
                }
                if (!StringUtil.isMobile(loginPhone)) {
                    showToast("请输入正确手机号码");
                    return;
                }
                if (CheckUtil.isNull(loginPwd)) {
                    showToast("请输入密码");
                    return;
                }
                presenter.login(mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是用户") ? 0 : 1, loginPhone, loginPwd);
                break;
            case R.id.btn_forget:
                ForgetPasswordActivity.open(mContext, mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是用户") ? 0 : 1);
                break;
            case R.id.iv_wechat:
                if (!JShareInterface.isAuthorize(Contants.weChat)) {
                    JShareInterface.authorize(Contants.weChat, mAuthListener);
                } else {
                    JShareInterface.removeAuthorize(Contants.weChat, mAuthListener);
                }
                break;
            case R.id.iv_qq:
                if (!JShareInterface.isAuthorize(Contants.qq)) {
                    JShareInterface.authorize(Contants.qq, mAuthListener);
                } else {
                    JShareInterface.removeAuthorize(Contants.qq, mAuthListener);
                }
                break;
            case R.id.btn_register:
                RegisterActivity.open(mContext);
                break;
            case R.id.tv_xieyi:
                presenter.loadArticleDetails(1);
                break;
            case R.id.tv_privacy:
                presenter.loadArticleDetails(11);
                break;
        }
    }

    AuthListener mAuthListener = new AuthListener() {
        @Override
        public void onComplete(Platform platform, int action, BaseResponseInfo data) {
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    if (data instanceof AccessTokenInfo) {        //授权信息
                        if (platform.getName().equals(Contants.weChat)) {//授权成功，获取个人信息
                            JShareInterface.getUserInfo(Contants.weChat, mAuthListener);
                        } else {
                            JShareInterface.getUserInfo(Contants.qq, mAuthListener);
                        }
                    }
                    break;
                case Platform.ACTION_REMOVE_AUTHORIZING://删除授权
                    if (platform.getName().equals(Contants.weChat)) {
                        JShareInterface.authorize(Contants.weChat, mAuthListener);
                    } else {
                        JShareInterface.authorize(Contants.qq, mAuthListener);
                    }
                    break;
                case Platform.ACTION_USER_INFO:
                    //个人信息原始数据，开发者可自行处理
                    if (data instanceof UserInfo) {      //第三方个人信息
                        String originData = data.getOriginData();
                        OriginDataDto dataDto = JsonUtil.fromJson(originData, OriginDataDto.class);
                        String openid = platform.getName().equals(Contants.weChat) ? dataDto.getUnionid() : ((UserInfo) data).getOpenid();
                        String name = ((UserInfo) data).getName();  //昵称
                        String imageUrl = ((UserInfo) data).getImageUrl();  //头像url
//                        LogUtil.e("LOGIN", "openid:" + openid + ",name:" + name + ",imageUrl:" + imageUrl);
                        presenter.loginThrid(mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是用户") ? 0 : 1, openid, name, imageUrl, platform.getName().equals(Contants.weChat) ? 1 : 2);
                    }
                    break;
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            LogUtil.e("LOGIN", "onError:" + platform + ",action:" + action + ",error:" + error);
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "授权失败";
                    break;
                case Platform.ACTION_REMOVE_AUTHORIZING:
                    toastMsg = "删除授权失败";
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "获取个人信息失败";
                    break;
            }
            showToast(toastMsg);
        }

        @Override
        public void onCancel(Platform platform, int action) {
            LogUtil.e("LOGIN", "onCancel:" + platform + ",action:" + action);
            String toastMsg = null;
            switch (action) {
                case Platform.ACTION_AUTHORIZING:
                    toastMsg = "取消授权";
                    break;
                case Platform.ACTION_USER_INFO:
                    toastMsg = "取消获取个人信息";
                    break;
            }
            showToast(toastMsg);
        }
    };

    @Override
    public void registerOrLoginSuccess(LoginInfoDto result) {
        saveInfo(result);
//        if (mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是商家")) {
//            saveInfo(result);
//        } else {
//            new Handler().postDelayed(() -> {
//                showLoading();
//                AuthHelper.getInstance().login(mContext, result.getHxId(), result.getHxPassword(), new AuthHelper.AuthCallback() {
//                    @Override
//                    public void onSuccess() {
//                        dismissLoading();
//                        saveInfo(result);
//                    }
//
//                    @Override
//                    public void onError(int errorCode, String errorStr) {
//                        dismissLoading();
//                        showToast("errorCode : " + errorCode + " ! errorStr : " + errorStr);
//                    }
//                });
//            }, 500);
//        }
    }

    private void saveInfo(LoginInfoDto result) {
        showToast("登录成功");
        UserInfoUtils.INSTANCE.saveLoginUserInfo(mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle(),result);
        registerJpush(result.getSessionId());
        if (mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是用户")) {//普通用户
            MainActivity.open(mContext);
        } else {//商家
            ShopMainActivity.open(mContext);
        }
    }

    //注册极光推送
    private void registerJpush(String sessionId) {
        TagAliasOperatorHelper.TagAliasBean tagAliasBean = new TagAliasOperatorHelper.TagAliasBean();
        tagAliasBean.action = ACTION_SET;
        sequence++;
        tagAliasBean.alias = sessionId;
        tagAliasBean.isAliasAction = true;
        TagAliasOperatorHelper.getInstance().handleAction(getApplicationContext(), sequence, tagAliasBean);
    }

    @Override
    public void showDetail(ArticleDetailDto result, int type) {
        WebViewActivity.open(mContext, type == 1 ? "用户协议" : "隐私协议", result.content);
    }

    @Override
    public void loginThird(LoginInfoDto result, Map<String, Object> params) {
        if (CheckUtil.isNull(result.getPhone())) {//没有绑定过，跳转绑定
            if (Integer.parseInt(params.get("loginType").toString()) == 0) {//普通用户
                Hawk.put(HawkKey.USER_AUTHENTICATION, result.getSessionId());
            } else {//商家
                Hawk.put(HawkKey.SHOP_AUTHENTICATION, result.getSessionId());
            }
            BindAccountActivity.open(mContext, (int) params.get("type"), mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle());
        } else {//登录成功
            if ((int) params.get("type") == 1) {
                Hawk.put(HawkKey.LOGIN_THIRD_TYPE, Contants.weChat);
            } else {
                Hawk.put(HawkKey.LOGIN_THIRD_TYPE, Contants.qq);
            }
            saveInfo(result);
//            if (mTabEntities.get(topMainTab.getCurrentTab()).getTabTitle().equals("我是用户")) {
//                new Handler().postDelayed(() -> {
//                    showLoading();
//                    AuthHelper.getInstance().login(mContext, result.getHxId(), result.getHxPassword(), new AuthHelper.AuthCallback() {
//                        @Override
//                        public void onSuccess() {
//                            dismissLoading();
//                            saveInfo(result);
//                        }
//
//                        @Override
//                        public void onError(int errorCode, String errorStr) {
//                            dismissLoading();
//                            showToast("errorCode : " + errorCode + " ! errorStr : " + errorStr);
//                        }
//                    });
//                }, 500);
//            } else {
//                saveInfo(result);
//            }
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode != RESULT_OK) return;
//        if (requestCode == 1001) {
//            finish();
//        }
//    }
}